﻿using lot.Map;
using Panuon.UI.Silver;
using System;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using lot.SDK;
using Panuon.UI.Silver.Core;
using System.Windows.Threading;
using System.Collections.Generic;

namespace lot
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : WindowX
    {
        public NASDK currsdk = null;
        public lotConfigs lotconfig = new lotConfigs();
        public NASDK nasdk;
        DispatcherTimer dtimer = new DispatcherTimer();
        float currentX = 0;
        float currentY = 0;
        //声明委托
        private delegate void UpdateMap();
        public MainWindow()
        {
            InitializeComponent();
        }

        private void WindowX_Loaded(object sender, RoutedEventArgs e)
        {
            //获取证书文件
            string certPath = AppDomain.CurrentDomain.BaseDirectory + "iot3rd.p12";
            if (File.Exists(certPath))
                lotconfig.cert = certPath;
            else
            {
                showErrorMessage("证书iot3rd.p12不存在程序根目录,请检查证书", "证书有误！");            //获取初始化各种参数
                Environment.Exit(0);
            }
            if (LotSetting.Default.first)
            {
                LotSetting.Default.first = false;
                LotSetting.Default.Save();
                showMessage("您是第一次启动本软件，请向开发商获取设备的ID号，配置物联网中心的DeviceId后使用，头像菜单中启动自动定位、警告开关，感谢使用！           Q:349380886", "首次启动", MessageBoxButton.OK, MessageBoxIcon.Info, "#75CD43", MessageBoxStyle.Modern);
            }
            browser_Initialized();
            radiomap.IsChecked = true;
            //配置

                
            lotconfig.appid = LotSetting.Default.appid;
            lotconfig.appkey = LotSetting.Default.appkey;
            lotconfig.certpwd = LotSetting.Default.certpwd;
            lotconfig.ip = LotSetting.Default.ip;
            lotconfig.port = LotSetting.Default.port;
            lotconfig.deviceid = LotSetting.Default.deviceid;

            settingform.TextBox_appid.Text = lotconfig.appid;
            settingform.TextBox_appkey.Text = lotconfig.appkey;
            settingform.TextBox_password.Text = lotconfig.certpwd;
            settingform.TextBox_IP.Text = lotconfig.ip;
            settingform.TextBox_IPPORT.Text = lotconfig.port;
            settingform.deviceid.Text = lotconfig.deviceid;
            settingform.timeslider.Value = LotSetting.Default.timerinterval;
            switchLocation.IsChecked = LotSetting.Default.location;
            switchSOS.IsChecked = LotSetting.Default.sos;
            switchFence.IsChecked = LotSetting.Default.fence;
            switchFall.IsChecked = LotSetting.Default.fall;

            settingform.savebutton.Click += Savebutton_Click;
            dtimer.Tick += new EventHandler(Dtimer_Tick);

            dtimer.Interval = TimeSpan.FromSeconds(LotSetting.Default.timerinterval);//间隔1秒
            if (LotSetting.Default.location)
            {
                dtimer.Start();
            }
        }

        //保存设置，重新初始化sdk
        private void Savebutton_Click(object sender, RoutedEventArgs e)
        {
            dtimer.Interval = TimeSpan.FromSeconds(settingform.timeslider.Value);
            
            lotconfig.appid = settingform.TextBox_appid.Text;
            lotconfig.appkey = settingform.TextBox_appkey.Text;
            lotconfig.certpwd = settingform.TextBox_password.Text;
            lotconfig.ip = settingform.TextBox_IP.Text;
            lotconfig.port = settingform.TextBox_IPPORT.Text;
            lotconfig.deviceid = settingform.deviceid.Text;

            LotSetting.Default.timerinterval = settingform.timeslider.Value;
            LotSetting.Default.appid = lotconfig.appid;
            LotSetting.Default.appkey = lotconfig.appkey;
            LotSetting.Default.certpwd = lotconfig.certpwd;
            LotSetting.Default.ip = lotconfig.ip;
            LotSetting.Default.port = lotconfig.port;
            LotSetting.Default.deviceid = lotconfig.deviceid;
            LotSetting.Default.Save();
            if (checkConfigEmpty())
            {
                showErrorMessage("配置信息有误，请检查配置或联系管理员！", "配置错误");
                return;
            }
            nasdk = new NASDK(lotconfig);
            showSuccessMessage("保存成功!", "物联网配置");
        }

        private void showSuccessMessage(string message, string title)
        {
            showMessage(message, title, MessageBoxButton.OK, MessageBoxIcon.Success, "#75CD43", MessageBoxStyle.Modern);
        }
        private void showErrorMessage(string message,string title)
        {
            showMessage(message, title, MessageBoxButton.OK, MessageBoxIcon.Error, "#FF4C4C");
        }
        private void showMessage(string msg,string title,MessageBoxButton button,MessageBoxIcon icon,string hexColor, MessageBoxStyle style = MessageBoxStyle.Classic)
        {
            MessageBoxX.Show(msg, title, Application.Current.MainWindow, button, new MessageBoxXConfigurations()
            {
                MessageBoxStyle = style,
                MessageBoxIcon = icon,
                ButtonBrush = hexColor.ToColor().ToBrush(),
            });
        }
        //定时定位
        private void Dtimer_Tick(object sender, EventArgs e)
        {
            if (!IsLoaded) return;
            if (checkConfigEmpty())
            {
                showErrorMessage("配置信息有误，请检查配置或联系管理员！", "配置错误");
                stop();
                return;
            }
            nasdk = new NASDK(lotconfig);
            CommonDefine.token = nasdk.getToken();
            if (CommonDefine.token == null)
            {
                showErrorMessage("无法获取Token,请检查配置或联系管理员！", "错误");
                return;
            }
            List<Device>  Devices = nasdk.GetDevices();
            if (Devices == null)
            {
                showErrorMessage("获取设备组失败，请检查配置或联系管理员！", "错误");
                stop();
                return;
            }
            Device device = Devices.Find(dev => dev.deviceId == lotconfig.deviceid);
            if (device == null)
            {
                showErrorMessage("无法找到设备ID为:\n" + lotconfig.deviceid + "的设备，请检查设备ID或者联系管理员", "错误");
                stop();
                return;
            }
            if (device.services == null || device.services.Count == 0)
            {
                showErrorMessage("该设备无任何服务信息，请联系管理员配置服务信息", "错误");
                stop();
                return;
            }
            //解析平台数据
            Dictionary<string,object> data = device.services[0].data;
            if (float.TryParse(data["Read_GPS_X"].ToString(),out currentX) && float.TryParse(data["Read_GPS_Y"].ToString(),out currentY))
        
            currentX /= 100;
            currentY /= 100;
            //debug
            //currentX = 31.56052F;
            //currentY = 117.2014F;

            gpsX.Text = currentX.ToString();
            gpsY.Text = currentY.ToString();
            if (currentX == 0 || currentY == 0)
            {
                return;
            }
            Dispatcher.BeginInvoke((Action)delegate ()
            {
                browser.InvokeScript("setLocation", new object[] { currentY, currentX });
            });
            int sos = int.Parse(data["Read_SOS"].ToString());
            int fall = int.Parse(data["Read_FALL"].ToString());
            //debug
            //sos = fall = 1;
            //求救警报
            if (LotSetting.Default.sos && sos == 1)
            {
                Dispatcher.BeginInvoke((Action)delegate ()
                {
                    Notice.Show("请注意，接收到老人求救信号，请及时处理或关闭检测!!!", "求救警报", 0.8, MessageBoxIcon.Warning);
                });
            }
            //摔倒警报
            if(LotSetting.Default.fall && fall == 1)
            {
                Dispatcher.BeginInvoke((Action)delegate ()
                {
                    Notice.Show("请注意，接收到老人摔倒信号，请及时处理或关闭检测!!!", "摔倒警报", 0.8, MessageBoxIcon.Warning);
                });
            }
        }
 
        private void stop()
        {
            dtimer.Stop();
            switchLocation.IsChecked = false;
        }

        //初始化地图
        private void browser_Initialized()
        {
            ObjectForScriptingHelper scriptingHelper = new ObjectForScriptingHelper();
            scriptingHelper.polyout += ScriptingHelper_polyout;
            browser.ObjectForScripting = scriptingHelper;
           
            Uri uri = new Uri("pack://application:,,,/lot;component/Resources/Bmap.html", UriKind.Absolute);
            Stream stream = Application.GetResourceStream(uri).Stream;
            using (StreamReader reader = new StreamReader(stream))
            {
                browser.NavigateToString(reader.ReadToEnd());
            }
        }

        private void ScriptingHelper_polyout()
        {
            if (LotSetting.Default.fence)
            {
                Dispatcher.BeginInvoke((Action)delegate()
                {
                    Notice.Show("请注意,检测到定位超出围栏范围,请及时处理或关闭检测!", "围栏警告", 0.9, MessageBoxIcon.Question);
                });
            }
        }

        public void SuppressScriptErrors(WebBrowser webBrowser, bool Hide)
        {
            FieldInfo fiComWebBrowser = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
            if (fiComWebBrowser == null) return;

            object objComWebBrowser = fiComWebBrowser.GetValue(webBrowser);
            if (objComWebBrowser == null) return;

            objComWebBrowser.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { Hide });
        }

        private void Web_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            //屏蔽网页脚本错误
            SuppressScriptErrors(sender as WebBrowser, true);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Environment.Exit(0);
        }

        private void Map_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (!IsLoaded)
            {
                return;
            }
        }

        private void RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton radioButton = sender as RadioButton;
            tabSetting.SelectedIndex = Convert.ToInt32(radioButton.Tag);
        }

        private void openAutoLocation(object sender, RoutedEventArgs e)
        {
            LotSetting.Default.location = true;
            LotSetting.Default.Save();
            LotSetting.Default.Reload();
            dtimer.Start();
        }

        private void closeAutoLocation(object sender, RoutedEventArgs e)
        {
            LotSetting.Default.location = false;
            LotSetting.Default.Save();
            dtimer.Stop();
        }

        private void openAutoFence(object sender, RoutedEventArgs e)
        {
            LotSetting.Default.fence = true;
            LotSetting.Default.Save();
        }

        private void closeAutoFence(object sender, RoutedEventArgs e)
        {
            LotSetting.Default.fence = false;
            LotSetting.Default.Save();
        }

        private void openAutoSOS(object sender, RoutedEventArgs e)
        {
            LotSetting.Default.sos = true;
            LotSetting.Default.Save();
        }

        private void closeAutoSOS(object sender, RoutedEventArgs e)
        {
            LotSetting.Default.sos = false;
            LotSetting.Default.Save();
        }


        private bool checkConfigEmpty() => 
                string.IsNullOrEmpty(lotconfig.deviceid)||
                string.IsNullOrEmpty(lotconfig.appid) ||
                string.IsNullOrEmpty(lotconfig.appkey) ||
                string.IsNullOrEmpty(lotconfig.certpwd) ||
                string.IsNullOrEmpty(lotconfig.ip) ||
                string.IsNullOrEmpty(lotconfig.port);

        private void WindowX_Closed(object sender, EventArgs e)
        {
            //Environment.Exit(0);
        }

        private void openAutoFall(object sender, RoutedEventArgs e)
        {
            LotSetting.Default.fall = true;
            LotSetting.Default.Save();
        }

        private void closeAutoFall(object sender, RoutedEventArgs e)
        {
            LotSetting.Default.fall = false;
            LotSetting.Default.Save();
        }
    }
}
